<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2 class="sidebar-title">在线教育平台</h2>
        <el-button icon="el-icon-menu" class="toggle-btn" @click="toggleSidebar"></el-button>
      </div>
      <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          background-color="#0b1b33"
          text-color="#fff"
          active-text-color="#409EFF"
          :collapse="isSidebarCollapse"
          router
      >
        <el-menu-item index="/stuhome">
          <el-icon><menu /></el-icon>
          <span>全部课程</span>
        </el-menu-item>
        <el-menu-item index="/myclass">
          <el-icon><menu /></el-icon>
          <span>我的课程</span>
        </el-menu-item>
        <el-menu-item index="/question">
          <el-icon><folder /></el-icon>
          <span>提问</span>
        </el-menu-item>
        <el-menu-item index="/stuper">
          <el-icon><user /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapse': isSidebarCollapse }">
      <!-- 面包屑（可根据实际需求调整） -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item>全部课程</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 页面标题与操作 -->
      <div class="page-header">
        <h1 class="page-title">全部课程</h1>
      </div>

      <!-- 搜索筛选区 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="搜索">
            <el-input v-model="searchForm.keyword" placeholder="请输入课程名称/讲师搜索" clearable />
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类">
              <el-option
                  v-for="category in courseCategories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="难度">
            <el-select v-model="searchForm.difficulty" placeholder="请选择难度">
              <el-option label="初级" value="初级"/>
              <el-option label="中级" value="中级"/>
              <el-option label="高级" value="高级"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 课程列表 -->
      <el-card class="course-list-card">
        <el-row :gutter="20">
          <el-col :span="8" v-for="course in courseList" :key="course.id">
            <el-card class="box-card">
              <img src="https://picsum.photos/300/200?random={{course.id}}" class="course-cover" alt="课程封面图">
              <div class="card-content">
                <div class="course-title">{{course.title}}</div>
                <div class="course-info">
                  <span class="teacher">讲师：{{course.teacherRealName}}</span>
                  <span class="category">{{course.categoryName}}</span>
                </div>
                <div class="course-details">
                  <span class="difficulty">难度：{{course.difficulty}}</span>
                  <span class="lessons">课时：{{course.lessons}}</span>
                </div>
                <div class="course-footer">
                  <el-button
                      v-if="!hasCourse(course.id)"
                      type="primary"
                      size="small"
                      @click="handleAddCourse(course)"
                  >
                    <el-icon><plus /></el-icon>加入学习
                  </el-button>
                  <el-button
                      v-else
                      type="success"
                      size="small"
                      disabled
                  >
                    <el-icon><check /></el-icon>已在学习
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[6, 12, 18]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
          />
        </div>
      </el-card>

      <!-- 成功提示消息 -->
      <el-message
          :visible="successMessageVisible"
          type="success"
          :message="successMessage"
          @close="successMessageVisible = false"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  Plus,
  Search,
  Refresh,
  Menu,
  User,
  Check
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request.js";

// 侧边栏相关状态
const isSidebarCollapse = ref(false)
const activeMenu = ref('allCourses')
const toggleSidebar = () => {
  isSidebarCollapse.value = !isSidebarCollapse.value
}

// 课程管理相关状态
const state = reactive({
  courseList: [], // 课程列表数据
  myCourseIds: [], // 已选课程ID列表
  total: 0, // 总记录数
  currentPage: 1, // 当前页码
  pageSize: 6, // 每页显示数量
  searchForm: {
    keyword: '', // 搜索关键词
    category: '', // 分类筛选
    difficulty: '' // 难度筛选
  },
  courseCategories: [
    { label: '前端开发', value: '前端开发' },
    { label: '后端开发', value: '后端开发' },
    { label: '移动开发', value: '移动开发' },
    { label: '人工智能', value: '人工智能' },
    { label: '大数据', value: '大数据' },
    { label: '云计算', value: '云计算' }
  ],
  successMessageVisible: false,
  successMessage: ''
})

const {
  courseList,
  myCourseIds,
  total,
  currentPage,
  pageSize,
  searchForm,
  courseCategories,
  successMessageVisible,
  successMessage
} = state

// 模拟获取课程列表数据
const fetchCourseList = () => {
  // 这里模拟接口请求，实际开发中替换为真实的 API 调用
  setTimeout(() => {
    courseList.splice(0, courseList.length)
    // 模拟返回的数据
    let mockData = [
      {
        id: 1,
        name: 'Vue3 实战教程',
        category: '前端开发',
        teacher: '张教授',
        difficulty: '中级',
        lessons: 24,
        status: '已发布'
      },
      {
        id: 2,
        name: 'Python 数据分析',
        category: '人工智能',
        teacher: '李老师',
        difficulty: '初级',
        lessons: 18,
        status: '已发布'
      },
      {
        id: 3,
        name: 'React 高级应用',
        category: '前端开发',
        teacher: '王讲师',
        difficulty: '高级',
        lessons: 30,
        status: '已发布'
      },
      {
        id: 4,
        name: 'Java 微服务架构',
        category: '后端开发',
        teacher: '赵教授',
        difficulty: '高级',
        lessons: 36,
        status: '已发布'
      },
      {
        id: 5,
        name: 'Flutter 跨平台开发',
        category: '移动开发',
        teacher: '陈老师',
        difficulty: '中级',
        lessons: 28,
        status: '已发布'
      },
      {
        id: 6,
        name: 'TensorFlow 深度学习',
        category: '人工智能',
        teacher: '刘教授',
        difficulty: '高级',
        lessons: 40,
        status: '已发布'
      },
      {
        id: 7,
        name: '大数据分析与应用',
        category: '大数据',
        teacher: '黄老师',
        difficulty: '中级',
        lessons: 32,
        status: '已发布'
      },
      {
        id: 8,
        name: '云原生技术入门',
        category: '云计算',
        teacher: '孙讲师',
        difficulty: '初级',
        lessons: 20,
        status: '已发布'
      }
    ]
      request('/course/findAll').then(Response => {
        mockData = Response.data;
        // 应用搜索筛选
        let filteredData = mockData
        if (searchForm.keyword) {
          const keyword = searchForm.keyword.toLowerCase()
          filteredData = filteredData.filter(course =>
              course.name.toLowerCase().includes(keyword) ||
              course.teacher.toLowerCase().includes(keyword)
          )
        }

        if (searchForm.category) {
          filteredData = filteredData.filter(course =>
              course.category === searchForm.category
          )
        }

        if (searchForm.difficulty) {
          filteredData = filteredData.filter(course =>
              course.difficulty === searchForm.difficulty
          )
        }

        courseList.push(...filteredData)
        total.value = filteredData.length
      })
  }, 500)
}

onMounted(() => {
  // 获取课程列表
  fetchCourseList()
  // 获取已选课程 ID 列表
  request('/student/course').then(response => {
    myCourseIds.length = 0
    myCourseIds.push(...response.data.map(course => course.courseId))
  })
})

// 搜索课程
const handleSearch = () => {
  currentPage.value = 1
  fetchCourseList()
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.category = ''
  searchForm.difficulty = ''
  fetchCourseList()
}

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchCourseList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchCourseList()
}

// 检查是否已选课程
const hasCourse = (courseId) => {
  return myCourseIds.includes(courseId)
}

// 添加课程
const handleAddCourse = (course) => {
  ElMessageBox.confirm(
      `确定要添加课程「${course.name}」吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
  ).then(async () => {
    try {
      // 修改接口调用，将课程 ID 写在路径上
      await request.post(`/student/addCourse/${course.id}`);
      myCourseIds.push(course.id);
      successMessage.value = `已成功添加课程「${course.name}」`;
      successMessageVisible.value = true;
      ElMessage({
        message: `已成功添加课程「${course.name}」`,
        type: 'success'
      })
    } catch (error) {
    }
  }).catch(() => {
    // 用户取消操作
  });
}

// 监听侧边栏折叠状态
watch(isSidebarCollapse, (newVal) => {
  // 可在此处添加侧边栏折叠后的额外逻辑
})
const courseHovered = ref(null)
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: #0b1b33;
  color: #fff;
  transition: width 0.3s ease-in-out;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  border-bottom: 1px solid #1f334b;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.toggle-btn {
  background: transparent;
  border: none;
  color: #fff;
  cursor: pointer;
  font-size: 20px;
}

.el-menu-vertical-demo {
  border-right: none;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  transition: margin-left 0.3s ease-in-out;
}

.sidebar-collapse .main-content {
  margin-left: 64px; /* 侧边栏折叠后，主内容区调整左边距 */
}

/* 面包屑样式 */
.breadcrumb {
  margin-bottom: 10px;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

/* 课程列表卡片样式 */
.course-list-card {
  margin-bottom: 20px;
}

/* 课程卡片样式 */
.box-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.box-card:hover {
  transform: translateY(-5px);
}

.course-cover {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.card-content {
  padding: 15px;
}

.course-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.teacher, .category {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.teacher {
  margin-right: 10px;
}

.course-details {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #909399;
  font-size: 13px;
}

.course-footer {
  text-align: right;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>

